﻿using LuckDraw.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LuckDraw.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult LuckDraw()
        {
            return View();
        }


        //需求:抽奖  
        //每个人只能被选中一次 
        [HttpPost]
        public JsonResult GetReward()
        {
            //单例创建容器
            Human humanObj = Human.GetInstance();
            //拿到人员数据
            var dictionary = Human.GetNameList();

            if (dictionary.Count == 0)
            {
                return Json(new { Data = "新年快乐", Success = true });
            }

            string luckName = DoLuckDraw(dictionary);

            return Json(new { Data = luckName, Success = true });
        }


        #region  抽奖实现
        //每个人只能被选中一次 递归抽奖过程
        /// <summary>
        /// 抽奖
        /// </summary>
        /// <param name="dictionary">人员字典</param>
        /// <returns></returns>
        public string DoLuckDraw(List<string> dictionary)
        {
            ////线程停止一下,避免计算太快 造成无线递归
            //Thread.Sleep(100);
            //随机数0-10
            Random random = new Random();
            var Lucky = random.Next(0, dictionary.Count - 1);

            var LuckyName = dictionary[Lucky];
            dictionary.RemoveAt(Lucky);

            return LuckyName;
        }
        #endregion



        [HttpPost]
        public void InitData()
        {
            Human.Init();
        }
    }
}